package org.hamster.common.services
{
	import mx.utils.ObjectUtil;
	
	import org.hamster.common.services.model.ConfigVO;
	import org.hamster.common.utils.CommonUtil;

	public class ConfigService
	{
		public function ConfigService()
		{
		}
		
		private static var _instance:ConfigService;
		
		public static function get instance():ConfigService
		{
			if (_instance == null) {
				_instance = new ConfigService();
			}
			return _instance;
		}
		
		public var configVO:ConfigVO;
		public var configClazz:Class;
		
		public function init(configXML:XML, configClazz_:Class = null):void
		{
			if (configXML == null || !configXML.hasOwnProperty('config')) {
				return;
			}
			
			configClazz = configClazz_;
			if (configClazz == null) {
				configClazz = ConfigVO;
			}
			
			configVO = new configClazz();
			
			var configNodeXML:XMLList = configXML.child("config");
			for each (var itemXML:XML in configNodeXML.children()) {
				var name:String = itemXML.name();
				if (configVO.hasOwnProperty(name)) {
					if (configVO[name] is Array) {
						if (configNodeXML[name] is XMLList) {
							var subArr:Array = [];
							for each (var subItemXML:XML in configNodeXML[name].children()) {
								subArr.push(subItemXML.toString());
							}
							configVO[name] = subArr;
						} else {
							configVO[name] = CommonUtil.toArray(configNodeXML[name]);
						}
					} else if (configVO[name] is int || configVO[name] is Number) {
						configVO[name] = parseFloat(itemXML);
					} else if (configVO[name] is Boolean) { 
						configVO[name] = "true" == itemXML.toString();
					} else {
						configVO[name] = itemXML.toString();
					}
				} else {
					configVO[name] = itemXML.toString();
				}
			}
		}
		
		public function toXML():XML
		{
			var resultXML:XML = <configList></configList>;
			var configXML:XML = <config></config>;
			resultXML.appendChild(configXML);
			
			var objInfo:Object = ObjectUtil.getClassInfo(configVO); 
			var fieldName:Array = objInfo["properties"] as Array; 
			for each(var q:QName in fieldName) {
				var property:String = q.localName;
				var value:* = configVO[property];
				if (property == "data" || value == null) {
					continue;
				}
				var xml:XML;
				if (value is Array) {
					for each (var v:* in value) {
						xml = new XML("<" + property + ">" + "</" + property + ">");
						xml[property] = v;
						configXML.appendChild(xml[property]);
					}
				} else {
					xml = new XML("<" + property + ">" + "</" + property + ">");
					xml[property] = value;
					configXML.appendChild(xml[property]);
				}
			}
			return resultXML;
		}
	}
}